package codegen

import (
	"gitee.com/hxchjm/goge/codegen/utils"
	"github.com/siddontang/go/config"
	"path/filepath"
)

const httpTemplate = `package http

import (
	"net/http"

	"{{.serviceName}}/api"
	"{{.serviceName}}/internal/model"

	"go-main/library/conf"
	"go-main/library/log"
	"go-main/library/net/http/dam"
)

var svc api.{{.serviceCamelName}}DamServer

// New a dam server.
func New(s api.{{.serviceCamelName}}DamServer) (engine *dam.Engine, err error) {
	var cfg dam.ServerConfig
	if err = conf.Bind("http", &cfg); err != nil {
		return
	}
	svc = s
	engine = dam.NewServer(&cfg)
	api.Register{{.serviceCamelName}}DamServer(engine, s)
	initRouter(engine)
	err = engine.Start()
	return
}

func initRouter(e *dam.Engine) {
	e.Ping(ping)
	g := e.Group("/xxx")
	{
		g.GET("/start", howToStart)
	}
}

func ping(ctx *dam.Context) {
	if _, err := svc.Ping(ctx, nil); err != nil {
		log.Error("ping error(%v)", err)
		ctx.AbortWithStatus(http.StatusServiceUnavailable)
	}
}

// example for http request handler.
func howToStart(c *dam.Context) {
	k := &model.ReqHello{
		Hello: "Golang 大法好 !!!",
	}
	c.JSON(k, nil)
}
`

func genHttp(dir, rootPkg string, cfg *config.Config, filename string) error {
	//name := strings.ToLower(api.Service.Name)
	//filename, err := format.FileNamingFormat(cfg.NamingFormat, name)
	//if err != nil {
	//	return err
	//}

	/*	filename := name
		configName := filename
		if strings.HasSuffix(filename, "-api") {
			filename = strings.ReplaceAll(filename, "-api", "")
		}*/
	svrCamelName := utils.SnakeToCamel(filepath.Base(rootPkg))
	return utils.GenFile(utils.FileGenConfig{
		Dir:          dir,
		Subdir:       httpDir,
		Filename:     filename,
		TemplateName: "mainTemplate",
		//Category:        category,
		//TemplateFile:    mainTemplateFile,
		BuiltinTemplate: httpTemplate,
		Data: map[string]string{
			//"importPackages": genHttpImports(rootPkg),
			"serviceName":      rootPkg,
			"serviceCamelName": svrCamelName,
		},
	})
}

/*func genHttpImports(parentPkg string) string {
	var imports []string
	imports = append(imports, fmt.Sprintf("\"%s\"", pathx.JoinPackages(parentPkg, diDir)))
	//imports = append(imports, fmt.Sprintf("\"%s/core/conf\"", vars.ProjectOpenSourceURL))
	//imports = append(imports, fmt.Sprintf("\"%s/rest\"", vars.ProjectOpenSourceURL))
	return strings.Join(imports, "\n\t")
}*/
